package com.common.file;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ding
 */
@Slf4j
public class ImageUtil {
    /**
     * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同
     */
    public static String combineImages(List<BufferedImage> imageList, String outPath) throws IOException {// 纵向处理图片
        if (CollectionUtils.isEmpty(imageList)) {
            return null;
        }

        int totalHeight = 0; // 总高度
        int totalWidth = 0; // 总宽度

        int picNum = imageList.size();// 图片的数量
        int[] heightArray = new int[picNum]; // 保存每个文件的高度
        List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
        for (int i = 0; i < picNum; i++) {
            BufferedImage buffer = imageList.get(i);
            int height = buffer.getHeight();// 图片高度
            heightArray[i] = height;
            if (i == 0) {
                totalWidth = buffer.getWidth();// 图片宽度
            }

            totalHeight += height; // 获取总高度
            int[] _imgRGB = new int[totalWidth * height];// 从图片中读取RGB
            _imgRGB = buffer.getRGB(0, 0, totalWidth, height, _imgRGB, 0, totalWidth);
            imgRGB.add(_imgRGB);
        }

        // 生成新图片
        int height = 0; // 设置偏移高度为0
        BufferedImage imageResult = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < picNum; i++) {
            if (i != 0) {
                int imgHeight = heightArray[i - 1];
                height += imgHeight; // 计算偏移高度
            }
            imageResult.setRGB(0, height, totalWidth, heightArray[i], imgRGB.get(i), 0, totalWidth); // 写入流中
        }

        if (StringUtils.isEmpty(outPath)) {
            outPath = "target/combined_image.jpg";
        }

        File outFile = new File(outPath);
        String ext = FilenameUtils.getExtension(outPath);
        ImageIO.write(imageResult, ext, outFile); // 写图片
        return outPath;
    }
}
